package com.rjt.permission;

import java.lang.reflect.Method;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ResponseBody;

import com.rjt.exception.NoAuthException;
import com.rjt.exception.NoLoginException;
import com.rjt.user.service.UserService;

@Aspect
@Component
public class ControllerAspect {

    private final static Logger logger = LoggerFactory.getLogger(ControllerAspect.class);

    @Autowired
    private UserService userService;

    /**
     * 定义切点
     */
    @Pointcut("(execution(public * com.rjt.*.controller.*.*(..)))")
    public void privilege() {
    }

    /**
     * 权限环绕通知
     *
     * @param joinPoint
     * @throws Throwable
     */
    @ResponseBody
    @Around("privilege()")
    public Object isAccessMethod(ProceedingJoinPoint joinPoint) throws Throwable {
    	//获取访问的目标类
    	String classType = joinPoint.getTarget().getClass().getName();
		Class<?> targetClass = Class.forName(classType);
		 //得到方法的访问权限
		final Permission classAccess = targetClass.getAnnotation(Permission.class);
        //获取访问目标方法
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        Method targetMethod = methodSignature.getMethod();
        //得到方法的访问权限
        final Permission methodAccess = targetMethod.getAnnotation(Permission.class);
        if(StringUtils.isEmpty(classAccess)) {
        	if(StringUtils.isEmpty(methodAccess)) {
        		 return joinPoint.proceed();
        	}else {
        		if(!userService.isLogin()) {
        			throw new NoLoginException();
        		}
        		
        		if(!userService.isAdmin()) {
       			 	throw new NoAuthException();
        		}else {
       			 	logger.info("您是管理员");
       			 	return joinPoint.proceed();
        		}
        	}
        }else {
        	if(!userService.isLogin()) {
    			throw new NoLoginException();
    		}
    		
    		if(!userService.isAdmin()) {
   			 	throw new NoAuthException();
    		}else {
   			 	logger.info("您是管理员");
   			 	return joinPoint.proceed();
    		}
        }
        
        
    }
    
}